/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *bstToGst(TreeNode *root)
    {
        int sum = 0;
        convert(root, sum);
        return root;
    }

    void convert(TreeNode *tree, int &sum)
    {
        if (tree == nullptr)
        {
            return;
        }
        convert(tree->right, sum);
        sum += tree->val;
        tree->val = sum;
        convert(tree->left, sum);
    }
};